<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { getIcon } from "@/api/assets/assets";

import DataMarketContent from './DataMarketContent.vue';
import type { Dataset } from '@/api/data/types/dataInfoCard';
import { useDatasetStore } from '@/stores/useDatasetsStore';

const dataSetStore = useDatasetStore();
const cardDataList = ref<Dataset[]>([]);

// 导入随机图片
const generatedImage8 = ref<string | null>(null);
const generatedImage9 = ref<string | null>(null);
const generatedImage10 = ref<string | null>(null);
const generatedImage11 = ref<string | null>(null)
const generatedImage12 = ref<string | null>(null);

const fetchIcon = async () => {
  try {
    const data = await getIcon(['8.png', '9.png', '10.png', '11.jpg', '12.png']);
    generatedImage8.value = data['8.png'];
    generatedImage9.value = data['9.png'];
    generatedImage10.value = data['10.png'];
    generatedImage11.value = data['11.jpg'];
    generatedImage12.value = data['12.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error);
  }
};
// 获取随机默认图片
const getRandomDefaultImage = () => {
  const defaultImages = [generatedImage8, generatedImage9, generatedImage10, generatedImage11, generatedImage12];
  const randomIndex = Math.floor(Math.random() * defaultImages.length);
  const value = defaultImages[randomIndex]?.value;
  return value ?? "default-image.jpg"; // 返回一个默认的图片值，如果为 null 或 undefined
};

// 获取数据集
const fetchCardData = async () => {
  // 使用 Pinia 的 usedataSetStore 获取课程数据
  const waitForDataLoad = async () => {
    while (!dataSetStore.isLoaded) {
      // JS promise 阻塞等待进程
      await new Promise(resolve => setTimeout(resolve, 200));
    }
  };
  await waitForDataLoad();

  cardDataList.value = dataSetStore.datasets.map(dataset => ({
    datasetId: dataset.datasetId,
    title: dataset.title,
    description: dataset.description,
    date: dataset.date,
    views: dataset.views,
    likes: dataset.likes,
    comments: 0, // 如果有评论数据，请替换此处
    downloads: dataset.downloads,
    shares: dataset.shares,
    username: dataset.username,
    favorites: dataset.likes,
    tags: dataset.tags,
    image: dataset.image ? dataset.image : getRandomDefaultImage(),
    link: dataset.link,
  }));
}

// 组件挂载时获取分类和数据
onMounted(async () => {
  fetchIcon();
  fetchCardData();
});

// 监视依赖项变化并获取数据
watch(() => dataSetStore.datasets, () => {
  fetchCardData();
});
</script>

<template>
  <div class="data-content">
    <div
      v-if="cardDataList.length > 0"
      style="width:100%; "
    >
      <DataMarketContent :apps="cardDataList" />
    </div>
    <div v-else>
      <p style="display:flex; align-items:center;">
        暂无数据
      </p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.data-content {
  margin-left:1.5rem;
  margin-right:-1rem;
}
</style>
